package cn.javablog.common.exception;

import cn.javablog.common.lang.Result;
import cn.javablog.controller.TUserController;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.ShiroException;
import org.apache.shiro.authc.ExpiredCredentialsException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletResponse;

@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {
    private final Logger logger = LoggerFactory.getLogger(TUserController.class);
//    // shiro异常
//    @ResponseStatus(HttpStatus.BAD_REQUEST)
//    @ExceptionHandler(value = ExpiredCredentialsException.class)
//    public Result handler(ExpiredCredentialsException e){
//        logger.error("shiro异常,没有权限：-------{}",e);
//        return Result.fail(401,"没有权限",null);
//    }
    // shiro异常
    @ResponseStatus(HttpStatus.OK)
    @ExceptionHandler(value = ShiroException.class)
    public Result handler(ShiroException e){
        logger.error("shiro异常,没有权限：-------{}",e);
        return Result.fail(401,"没有权限",null);
    }
    // 运行异常
    @ResponseStatus(HttpStatus.OK)
    @ExceptionHandler(value = RuntimeException.class)
    public Result handler(RuntimeException e){
        logger.error("运行时异常：-------{}",e);
        return Result.fail(e.getMessage());
    }
    // 实体异常
    @ResponseStatus(HttpStatus.OK)
    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public Result handler(MethodArgumentNotValidException e,ServletResponse response){
        logger.error("注解异常：-------{}",e);
        BindingResult bindingResult = e.getBindingResult();
        ObjectError objectError = bindingResult.getAllErrors().stream().findFirst().get();
        return Result.fail(objectError.getDefaultMessage());

    }
    //Assert
    @ResponseStatus(HttpStatus.OK)
    @ExceptionHandler(value = IllegalArgumentException.class)
    public Result handler(IllegalArgumentException e){
        logger.error("Assert异常:------{}",e);
        return Result.fail(e.getMessage());
    }
}
